/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2019/12/31 15:18
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.oauth2.handler;

import com.spring.arch.common.utils.HttpUtils;
import com.spring.arch.common.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证成功监听器
 *
 * @author Frank
 * @version 1.0.0.1
 * @since 2019/12/31 15:18
 */
@Slf4j
@Component
public class AuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Autowired
    private HttpServletRequest request;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        // 账号密码登录成功和token认证成功 都会推出AuthenticationSuccessEvent事件，可以根据事件源进行更细的控制，
        // 这里的事件源除了登录事件(UsernamePasswordAuthenticationToken)，还有可能是token验证事件源(OAuth2Authentication)
        Object source = event.getSource();
        if (source == null) {
            log.error("event source is Empty!!!");
            return;
        }
        Class<?> sourceClass = source.getClass();
        if (sourceClass.isAssignableFrom(UsernamePasswordAuthenticationToken.class)) {
            // 记录登录日志
            Authentication authentication = event.getAuthentication();
//            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            if (attributes != null) {
//                HttpServletRequest request = attributes.getRequest();
//
//            }
            String clientIP = HttpUtils.getClientIP(request);
            log.info("[{}] - [{}] authentication success!!!", clientIP, authentication.getName());
        } else if (sourceClass.isAssignableFrom(OAuth2Authentication.class)) {
            log.info("Oauth2 authentication success!!!");
        }
    }
}
